package com.ruoyi.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gg.reader.api.dal.GClient;
import com.gg.reader.api.protocol.gx.EnumG;
import com.gg.reader.api.protocol.gx.MsgBaseInventoryEpc;
import com.gg.reader.api.protocol.gx.MsgBaseStop;
import com.ruoyi.cangchu.domain.TZhgdPersonAttnH;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.service.ITZhgdDeviceToolsStorageHistoryService;
import com.ruoyi.system.service.RFIDClientService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.Map;

@EnableAsync
@Service
public class RFIDClientServiceImpl implements RFIDClientService {
    @Autowired
    private ITZhgdDeviceToolsStorageHistoryService toolsStorageHistoryService;

    private static final Logger log = LoggerFactory.getLogger(RFIDClientServiceImpl.class);
    static String pathUrl="192.168.0.30:8160";
    private static class GClientHandel {
        static final GClient service = new GClient();
    }
    //人员进入
    @Override
    @Async
    public void verify(Map<String, Object> result, TZhgdPersonAttnH personAttnH) {
            if("1".equals(String.valueOf(result.get("Direction"))) ){    //扫脸进入
                openTcp(GClientHandel.service, pathUrl,personAttnH);    //开启仓储扫描功能  持续扫描
            }
            if("2".equals(String.valueOf(result.get("Direction"))) ){    //扫脸出
                closeRfid(GClientHandel.service,pathUrl,personAttnH,false);
            }
    }


    //心跳上报

    public String heartbeat(@RequestBody String body) {
        String result = "{\"code\": 500,\"desc\": \"error\"}";

        JSONObject data = JSON.parseObject(body);
        String operator = data.getString("operator");
        if("HeartBeat".equals(operator)){
            result = "{\"code\": 200,\"desc\": \"OK\"}";
            JSONObject info = data.getJSONObject("info");
            String deviceID = info.getString("DeviceID");
            // TODO 可以根据心跳上报来判断设备在线状态，30秒
            System.out.println("heartbeat=========================");
            System.out.println(data.toJSONString());
            System.out.println(deviceID);
            System.out.println("heartbeat=========================");
        }
        return result;
    }

    public boolean openTcp(GClient client, String path,TZhgdPersonAttnH personAttnH) {
        log.info("仓储门禁人员信息"+personAttnH);
        if (client.openTcp(path, 2000)) {
            subscribeHandler(client,personAttnH);
            MsgBaseInventoryEpc msgBaseInventoryEpc = new MsgBaseInventoryEpc();
            msgBaseInventoryEpc.setAntennaEnable(EnumG.AntennaNo_1);
            msgBaseInventoryEpc.setInventoryMode(EnumG.InventoryMode_Inventory);
            client.sendSynMsg(msgBaseInventoryEpc);
            if (0x00 == msgBaseInventoryEpc.getRtCode()) {
                log.info("仓储设备已经连接成功");
                return true;
            } else {
                log.info("存在连接---");
                //closeRfid(client,path,true);
            }
        }

        log.info("仓储设备已经连接成功");
        try {
            Thread.sleep(1000*30*60);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        closeRfid(GClientHandel.service,pathUrl,personAttnH,false);
        return true;
    }

    /**
     * @Description:关闭
     * @param
     * @return: ExecutionResult
     * @Author: wuyafeng
     * @Date: 2024/6/14 18:25
     */

    public TableDataInfo closeRfid(GClient client, String path, TZhgdPersonAttnH personAttnH,boolean flag) {
        TableDataInfo resDate=new TableDataInfo();
        MsgBaseStop stopMsg = new MsgBaseStop();
        client.sendSynMsg(stopMsg);
        if (0x00 == stopMsg.getRtCode()) {
            log.info("关闭仓储设备连接");
        } else {
            log.info("关闭仓储设备连接 Fail");
            resDate.setCode(200);
            resDate.setMsg("关闭仓储设备连接 Fail\"");
            return resDate;
        }
        client.close();
        if(flag){
            openTcp(client,path,personAttnH);
        }
        resDate.setCode(200);
        resDate.setMsg("关闭仓储设备连接 Fail\"");
        return resDate;
    }

    /**
     * @Description:仓储设备扫描 订阅 获取扫描的设备ID
     * @param	client
     * @Author: wuyafeng
     * @Date: 2024/9/13 17:41
     */

    public void subscribeHandler(GClient client,TZhgdPersonAttnH personAttnH) {
        client.onTagEpcLog = (s, logBaseEpcInfo) -> {
            if (null != logBaseEpcInfo && logBaseEpcInfo.getResult() == 0) {
                log.info("获取订阅数据:"+logBaseEpcInfo);
                if(StringUtils.isNotEmpty(logBaseEpcInfo.getEpc())){
                    toolsStorageHistoryService.savaHistory(logBaseEpcInfo.getEpc(),personAttnH);//获取扫描设备，写入记录库
                }
            }
        };
        client.onTagEpcOver = (s, logBaseEpcOver) -> System.out.println("获取订阅任务关闭");
    }
}


